package org.web.ssm.service.wechatService.wechatServiceImpl;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.web.ssm.model.wechatModel.AccessToken;
import org.web.ssm.model.wechatModel.Menu;
import org.web.ssm.model.wechatModel.Openid;
import org.web.ssm.service.wechatService.IWechatService;
import org.web.ssm.utils.HttpClientUtils;

import java.io.IOException;

/**
 * Created by LUOLIANG on 2016/6/3.
 */
@Service
public class WecahtServiceImpl implements IWechatService {
    private static final String APPID = "wx80d0e5daca21e02e";            //应用ID
    private static final String APPSECRET = "1540dae56a361f23a5d4df887d2cc7d6";            //应用密钥
    //获取全局accesstoken请求地址
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    //创建菜单请求地址
    private static final String MENU_CREATE_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
    //
    private static final String OAUTH_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

    @Override
    @Transactional
    public AccessToken getAccessToken() {
        String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);

        String result = HttpClientUtils.doGetStr(url);

        AccessToken accessToken = JSON.parseObject(result, AccessToken.class);

        return accessToken;
    }

    @Override
    public String createMenu(Menu menu) {
        AccessToken accessToken = getAccessToken();
        String result = "";
        String url = MENU_CREATE_URL.replace("ACCESS_TOKEN", accessToken.getAccess_token());

        try {
            result = HttpClientUtils.doPostStr(url, JSON.toJSONString(menu));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    public String getOpenid(String code) {
        String url = OAUTH_ACCESS_TOKEN_URL.replace("APPID", APPID).replace("SECRET", APPSECRET).replace("CODE", code);

        String result = HttpClientUtils.doGetStr(url);

        Openid openid = JSON.parseObject(result, Openid.class);

        return openid.getOpenid();
    }
}
